import category from '../../services/cms/category';

export default {
  namespace: 'category',

  state: {
    data: {
      list: [],
      pagination: {},
    },
  },

  effects: {
    *fetch({ payload }, { call, put }) {
      const params = payload
        ? {
            page: payload.currentPage,
            size: payload.pageSize,
          }
        : {};
      const response = yield call(category.query, params);

      response.data.list.forEach(item => {
        const o = item;
        o.key = item.category_id;
      });

      yield put({
        type: 'save',
        payload: response.data,
      });
    },
    *add({ payload, callback }, { call, put }) {
      const response = yield call(category.add, { ...payload });
      yield put({
        type: 'save',
        payload: response.data,
      });
      if (callback) callback();
    },
    *remove({ payload, callback }, { call, put }) {
      const response = yield call(category.remove, { ...payload });
      yield put({
        type: 'save',
        payload: response.data,
      });
      if (callback) callback();
    },
  },

  reducers: {
    save(state, action) {
      return {
        ...state,
        data: action.payload,
      };
    },
  },
};
